package org.yesin.user.service;

import com.yesin.geteway.utils.NumberUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.yesin.user.mapper.UserMapper;
import org.yesin.user.pojo.User;
import org.yesin.user.utils.CodeUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    static final String KEY_PREFIX = "user:verify:";

    static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    /**
     * 校验数据是否可用（是否已存在）
     *
     * @param data
     * @param type
     * @return
     */
    public Boolean checkUser(String data, Integer type) {
        User record = new User();
        if (type == 1) { //校验用户名
            record.setUsername(data);
        } else if (type == 2) {
            record.setPhone(data);
        } else {
            return null;
        }
        return this.userMapper.selectCount(record) == 0;
    }

    public Boolean sendVerifyCode(String phone) {
        if (StringUtils.isBlank(phone)) {
            LOGGER.error("手机号码为空~~");
            return false;
        }
        // 生成验证码
        String code = NumberUtils.generateCode(6);
        try {
            // 发送短信
            Map<String, String> msg = new HashMap<>();
            msg.put("phone", phone);
            msg.put("code", code);
//            this.amqpTemplate.convertAndSend("sms.code", msg);
            // 将验证码存入redis
            this.redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
            return true;
        } catch (Exception e) {
            LOGGER.error("短信发送失败 phone:{}, code: {}", phone, code);
            return false;
        }
    }

    public void register(User user, String code) {
        // 查询redis中的验证码
        String redisCode = this.redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        // 1.校验验证码
        if (!StringUtils.equals(code, redisCode)) {
            return;
        }
        // 2.生成盐
        String salt = CodeUtils.generateSalt();
        user.setSalt(salt);
        // 3.加盐加密
        user.setPassword(CodeUtils.md5Hex(user.getPassword(), salt));
        // 4.新增用户
        user.setId(null);
        user.setCreated(new Date());
        this.userMapper.insertSelective(user);

        // 删除redis缓存
        redisTemplate.delete(KEY_PREFIX + user.getPhone());
    }

    public User query(String username, String password) {
        // 根据username查询User
        User record = new User();
        record.setUsername(username);
        User user = this.userMapper.selectOne(record);
        // 获取salt
        String slat = user.getSalt();
        // password + salt 加密
        if (!user.getPassword().equals(CodeUtils.md5Hex(password, slat))) {
            return null;
        }
        return user;
    }
}
